# -*- coding: utf-8 -*-
from google.appengine.dist import use_library
use_library('django', '1.2')

import logging
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import xmpp_handlers
from google.appengine.ext import webapp,db
from google.appengine.api import xmpp

from db import User
class botmsg:
	missing_ppl	= u"%s est introuvable dans mes registre. J'en suis navré."
	nopass		= u"%s n'a pas choisi de mot de passe."
	badmatch	= u"Le mot de passe de %s n'est pas %s"
	confirm		= u"Votre adresse est bien enregistrée comme celle de %s"
	misc		= ''.join((
				u"Bonjour. Pour vous enregistrer, merci d'utiliser",
				u" la commande \"/register pseudo pass\""))
	unhandled	= ''.join((
				u"Bonjour. Merci d'utiliser la commande \"/register ",
				u"pseudo pass\". Si vous n'avez pas de mot de passe, ",
				u"veuillez en choisir un sur http://hordes-mp.appspot.",
				u"com/set"))

class Bot(xmpp_handlers.CommandHandler):
	def register_command(self, message=None):
		logging.info('register_command')
		args = message.arg.split(' ', 1)
		ppl = User.all().filter('name', args[0].lower()).get()
		# player doesn't exist
		if ppl is None:
			message.reply(botmsg.missing_ppl % args[0])
		# player haven't choose a password.
		elif not ppl.imPass:
			message.reply(botmsg.nopass % args[0])
		# password doesn't match. bad.
		elif args[1] != ppl.imPass:
			message.reply(botmsg.badmatch % (args[0], args[1]) )
		# everything look fine
		else:
			ppl.im = db.IM(u'xmpp', message.sender)
			xmpp.send_message([ppl.im.address],
								botmsg.confirm % args[0])
			ppl.put()


	def unhandled_command(self, message=None):
		message.reply(botmsg.unhandled)
	def text_message(self, message=None):
		message.reply(botmsg.misc)

application = webapp.WSGIApplication([
						('/_ah/xmpp/message/chat/',Bot),
									],
									debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
		main()
